

var rootUrl = Global_LinkPath;
/**
 * Ajax 설정
 *
 * 사용법 : $.goAjax(url, params, callback, datatype);
 * url : full path
 * params : name1=value1&name2=value2&name3=value3
 * callback : 콜백 받을 함수 명 function 콜백함수(data)로 재정의함
 * datatype : html, xml, json 등으로 사용 (null 이면 html)
 */
(function($j) {
$j.goAjax = function(url, params, proc, datatype, basync)
	{
		if(datatype == null || $j.trim(datatype) == '')
			datatype = 'html';
		
		if(basync == null)
			basync = true;
		
		$j.ajax({
			success : proc,
			type: 'POST',
			url: url,
			data: params,
			dataType: datatype,
			async : basync,
			domain: document.domain
		});
		
	};
})(jQuery);

//Main / Sub 같이 사용함
function setDefaultDeviceForFlash(deviceID)
{	
	$j.goAjax(rootUrl + "/ajax/setDefaultDevice.as", "defaultDevice=" + deviceID,
			function(data){
				try {
					//Main 에서 reload 되도록 함. mainDevice(g) 에서는 아무 처리 하지 않음
					swf_name = document.getElementById("mainDeviceFlashLayer");
					swf_name.style.display = "none";
					var url = location.href;
					if(url.indexOf('/main/getMain.as') > -1)
					{
						location.href = rootUrl + '/main/getMain.as';
					}
					else
					{
						location.reload();
					}
				}catch (e){
					//Sub 에서  reload 되도록 함. 
					swf_name = document.getElementById("selectDeviceFlashBig");
					swf_name.style.display = "none";
					var url = location.href;
					
					if(url.indexOf('/topApps/topAppsDetail.as') > -1 || url.indexOf('/topApps/getSellerList.as') > -1 || url.indexOf('/topApps/topAppsList.as') > -1 || url.indexOf('/topApps/smart.as') > -1)
					{
						location.href = rootUrl + '/topApps/topAppsList.as?categoryID=all';
					}
					else
					{
						location.reload();
					}
				}
			}
	, 'json');
}

//사용 안함 2011.11.04
//OTA 적용 하면서 setDefaultDeviceForFlash로 변경됨
function setDefaultDevice(deviceID, deviceName, deviceImg, cateId)
{
	$j.post(rootUrl + "/ajax/setDefaultDevice.as", "defaultDevice=" + deviceID,
			function(data){
				var selectDeviceHtml = '';
				var displayDeviceNm = getProductNm(deviceName);
				var displayDeviceNm2 = getProductNm2(deviceName);
				try{
					if(deviceID == null || deviceID=='')
					{
						selectDeviceHtml += "<div class='device-img'><img src='"+Global_DepthPathImage+"/common/images/lnb_device_all.gif' alt='All' width='58' height='58' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" /></div>";
						selectDeviceHtml += "<div class='select-right'>";
						selectDeviceHtml += "<p>"+ $j("#allphoneValue").val() +"</p>";
						selectDeviceHtml += "<em></em>";
					}
					else
					{
						selectDeviceHtml += "<div class='device-img'><img src='"+deviceImg+"' alt='"+deviceName+"' width='58' height='58' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" /></div>";
						selectDeviceHtml += "<div class='select-right'>";
						selectDeviceHtml += "<p>" + displayDeviceNm;// + "</p>";
						//selectDeviceHtml += "<em>(" + deviceID + ")</em>";
					}
					selectDeviceHtml += "<a href='javascript:selectDevice();' class='btn9'><span><span><span><span>"+ $j("#selectdeviceValue").val() +"</span></span></span></span></a>";
					selectDeviceHtml += "</div>";
					$j('#selectDevice').empty();
					$j('#selectDevice').append($j(selectDeviceHtml));
					
					var leftHtmlLayer = '';
					
					if(deviceID == null || deviceID=='')
					{
						leftHtmlLayer += "<p><img src='"+Global_DepthPathImage+"/common/images/lnb_device_all.gif' alt='All' /></p>";
						leftHtmlLayer += "<strong>"+ $j("#allphoneValue").val() +"</strong>";
						leftHtmlLayer += "<em></em>";
					}
					else
					{
						leftHtmlLayer += "<p><img src='"+deviceImg+"' alt='"+deviceName+"' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\"/></p>";
						leftHtmlLayer += "<strong>"+displayDeviceNm2;//+"</strong>";
						//leftHtmlLayer += "<em>("+deviceID+")</em>";
					}
					leftHtmlLayer += "<div>"+ $j("#selectphoneValue").val() +"</div>";
					$j('#leftDevice').empty();
					$j('#leftDevice').append($j(leftHtmlLayer));
					
				}
				catch(e)
				{
					
				}
				
				var params = '?categoryID=';
				if(cateId == null || cateId == 'undefined'){
					params = '';
				}
				else{
					params = params + cateId;
				}
				var url = location.href;
				
				if(url.indexOf('/topApps/topAppsGate.as') > -1)
				{
					location.href = rootUrl + '/topApps/topAppsGate.as';//window.location.reload();
				}				
				else
				{
					location.href = rootUrl + '/topApps/topAppsList.as' + params;
				}
			}
	);
	
}
function getProductNm(prdNm)
{
	var tmp = prdNm;
	var idx = prdNm.indexOf("(");
	if(idx>-1)
	{
		prdNm = prdNm.replace("(", "</p><em>(");
		prdNm = prdNm.replace(")", ")</em>");
	}
	else{
		prdNm= prdNm + "</p><em></em>";
	}
	
	return prdNm;
}

function getProductNm2(prdNm)
{
	var tmp = prdNm;
	var idx = prdNm.indexOf("(");
	if(idx>-1)
	{
		prdNm = prdNm.replace("(", "</strong><em>(");
		prdNm = prdNm.replace(")", ")</em>");
	}
	else{
		prdNm=prdNm + "</strong><em></em>";
	}
	return prdNm;
}
function initLeft(cateId)
{	
	var selectedDeviceID = '';
	$j.goAjax(rootUrl + "/ajax/getDefaultDevice.as", "", function(data){
		selectedDeviceID = data[data.countryCd];
	}, "json", false);
	
	$j.getJSON(rootUrl + "/main/getDevicesJson.as", "",
			function(data){
			var html = "";
			html += "<li>";
			html += "	<a href=\"javascript:;\" onclick=\"javascript:setDefaultDevice('', '', '"+Global_DepthPathImage+"/common/images/lnb_device_all.gif', '"+cateId+"');\">";
			html += "		<span><img src='"+Global_DepthPathImage+"/common/images/lnb_device_all.gif' alt='"+$j("#allphoneValue").val()+"' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" /></span>";
			html += "		<strong>"+$j("#allphoneValue").val()+"</strong>";
			html += "	</a>";
			html += "</li>";
			if (data != null) {
				data = data.deviceList;
				for (var i = 0; i < data.length; i++) {
					var v = data[i];
					var deviceImg = Global_Image_Domain + v.deviceImg;
					var deviceName = v.countryDeviceName;
					var deviceID = v.deviceID;
					var displayDeviceNm = getProductNm(deviceName);
					var displayDeviceNm2 = getProductNm2(deviceName);
					if(selectedDeviceID == '')
					{
						//공백일경우
					}
					else
					{
						if(deviceID == selectedDeviceID)
						{
							
							var selectDeviceHtml = '';
							selectDeviceHtml += "<div class='device-img'><img src='"+deviceImg+"' alt='"+deviceName+"' width='58' height='58' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" /></div>";
							selectDeviceHtml += "<div class='select-right'>";
							selectDeviceHtml += "<p>" + displayDeviceNm;// + "</p>";
							//selectDeviceHtml += "<em>(" + deviceID + ")</em>";
							selectDeviceHtml += "<a href='javascript:selectDevice();' class='btn9'><span><span><span><span>"+ $j("#changedeviceValue").val() +"</span></span></span></span></a>";
							selectDeviceHtml += "</div>";
							$j('#selectDevice').empty();
							$j('#selectDevice').append($j(selectDeviceHtml));
							
							var leftHtmlLayer = '';
							leftHtmlLayer += "<p><img src='"+deviceImg+"' alt='"+deviceName+"' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" width='58' height='58'/></p>";
							leftHtmlLayer += "<strong>"+displayDeviceNm2;//+"</strong>";
							//leftHtmlLayer += "<em>('"+deviceID+"')</em>";
							leftHtmlLayer += "<div>"+ $j("#selectphoneValue").val() +"</div>";
							$j('#leftDevice').empty();
							$j('#leftDevice').append($j(leftHtmlLayer));
						}
					}
					
					html += "<li>";
					html += "	<a href=\"javascript:;\" onclick=\"javascript:setDefaultDevice('" + deviceID + "', '"+deviceName+"', '"+deviceImg+"', '"+cateId+"');\">";
					html += "		<span><img src='" + deviceImg +"' alt='"+ deviceName +"' onerror=\"this.src='" + Global_DepthPathImage + "/common/images/lnb_device_all.gif'\" width='58' height='58' /></span>";
					html += "		<strong>"+deviceName+"</strong>";
					html += "	</a>";
					html += "</li>";
				}
				
				if(selectedDeviceID == '')
				{
					var selectDeviceHtml = '';
					selectDeviceHtml += "<div class='device-img'><img src='"+Global_DepthPathImage+"/common/images/lnb_device_all.gif' alt='' width='58' height='58' /></div>";
					selectDeviceHtml += "<div class='select-right'>";
					selectDeviceHtml += "<p></p>";
					selectDeviceHtml += "<em></em>";
					selectDeviceHtml += "<a href='javascript:selectDevice();' class='btn9'><span><span><span><span>"+ $j("#selectdeviceValue").val() +"</span></span></span></span></a>";
					selectDeviceHtml += "</div>";
					$j('#selectDevice').empty();
					$j('#selectDevice').append($j(selectDeviceHtml));
					
					var leftHtmlLayer = '';
					leftHtmlLayer += "<p><img src='"+Global_DepthPathImage+"/common/images/lnb_device_all.gif' alt='' /></p>";
					leftHtmlLayer += "<strong></strong>";
					leftHtmlLayer += "<em></em>";
					leftHtmlLayer += "<div>"+ $j("#selectphoneValue").val() +"</div>";
					$j('#leftDevice').empty();
					$j('#leftDevice').append($j(leftHtmlLayer));
				}
				
				$j('#deviceList').append($j(html));
				
				return html;
			}
	});
}

jQuery(document).ready(function() {
	$j("#sfcForm").click(function() {
		$j("#sfcForm").ajaxForm({
			clearForm: true,
			url: "checkSignUpBySFCMember.as",
			dataType: 'json',
			beforeSubmit: function() {
				$j.fancybox.showActivity();
				
				if( !$j("#sfcForm").valid() ){
					$j.fancybox.hideActivity();
					return false;
				}
			},
			success: function(data) {
				$j.fancybox.hideActivity();
				if (data.SFC == "fail") {
					alert(data.message);
				}
				if (data.SFC == "success") {
					$j.fancybox.close();
					$j("#mobileMember").remove();
					$j("#signUp p.desc").text(data.ospdesc);
					$j("#emailID").attr("value", data.emailID);
					$j("#firstName").attr("value", data.firstName);
					$j("#lastName").attr("value", data.lastName);
					$j("#birthDate option").each(function() {
						if ($j(this).val() == data.birthDate) {
							$j(this).attr("selected", "selected");
						}
					});
					$j("#birthMonth option").each(function() {
						if ($j(this).val() == data.birthMonth) {
							$j(this).attr("selected", "selected");
						}
					});
					$j("#birthYear option").each(function() {
						if ($j(this).val() == data.birthYear) {
							$j(this).attr("selected", "selected");
						}
					});
					$j("#signupForm #password").focus();
				}
			}
		});
	});
	
	$j(".external").click(function(){
		window.open(this.href);
		return false;
	}).attr("title", "Opens in a new window");
	
	$j.validator.addMethod("noSpecialChars", function(value, element) {
		return this.optional(element) || /^[a-z0-9\!\@\*\$\^\%\&]+$/i.test(value);
	});
	
	$j.validator.addMethod("noSpecialOnEmail", function(value, element) {
		return this.optional(element) || /^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*$/i.test(value);
	});
	
	// <, > 문자 입력 못하도록 제한
	$j.validator.addMethod("notPermitionChars", function(value, element, param) {
		if(value.indexOf(">") > -1 || value.indexOf("<") > -1 ){
			return false;
		}
		return true;
	});
	
	//윤년 제한
	var leapCheck = function(param){
		//alert(1);
		if( ( 0 == param.year % 4 && 0 != param.year % 100 ) || 0 == param.year % 400 ){
			if( param.day > 29 ) return false;
		} else {
			if( param.day > 28 ) return false;
		}
		return true;
	};
	
	var monthsCheck = function(param){
		var months = [ 0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
		if( param.day > months[Number(param.month)] )
			return false;
		
		return true;		
	};
	
	var currentTimeCompare = function(param){
		var curr = new Date();
		if( curr.getFullYear() < param.year ||
			( curr.getFullYear() == param.year  && curr.getMonth() +1 < param.month ) ||
			( curr.getFullYear() == param.year && curr.getMonth() +1 == param.month && curr.getDate() < param.day ) )
			return false;
		return true;
	};	
	
	$j.validator.addMethod("dateCheck", function(value, element, param) {
		
		if( 0 == param.month.length || 0 == param.year.length || 0 == param.day.length ){
			return true;
		}
		
		if( 2 == param.month && !leapCheck(param) ) 
			return false;
		else if( 2 != param.month && !monthsCheck( param ))
			return false;
		else if( !currentTimeCompare(param) )
			return false;
		
		return true;
	});
	
	$j.validator.addMethod("minorCheck", function(value, element, param) {
		
		if( 0 == param.month.length || 0 == param.year.length || 0 == param.day.length ){
			return true;
		}
		var MAX_DIFF_YEAR = param.max;
		
		var curr = new Date();
		var diffYear  = curr.getFullYear() - param.year;
		var diffMonth = curr.getMonth() +1 - param.month;
		var diffDay   = curr.getDate()     - param.day;
		if( diffYear > MAX_DIFF_YEAR ||
			( diffYear == MAX_DIFF_YEAR && diffMonth > 0 ) ||
			( diffYear == MAX_DIFF_YEAR && diffMonth == 0 && diffDay >= 0 ) ){
			return true;
		}
		return false;
	});
	
	//$j(".close.iframe").live("click", parent.$j.fancybox.close);
});

function movplay(){     
    try {getSWF("s8500flash").stopVod();} catch (e){}
    try {getSWF("i8000flash").stopVod();} catch (e){}
    try {getSWF("i80002flash").stopVod();} catch (e){}
    try {getSWF("i8000uflash").stopVod();} catch (e){}
    try {getSWF("omniai8000flash").stopVod();} catch (e){}
    try {getSWF("ami8000flash").stopVod();} catch (e){}
    try {getSWF("tutorial1").stopVod();} catch (e){}
}

function getSWF(movieName){ 
	   if(navigator.appName.indexOf("Microsoft")!= -1){
	              return window[movieName];
	   }else{
	              return document[movieName];
	   }
	}


//2011-09-27
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function getTerms() {

    var f2 = document.frm_footer;

    $('toggleterms01').onclick = "";
    if (f2.tempClickTerms.value=="Y") {
        return;
    }
    f2.tempClickTerms.value="Y";
    
    var mcCode = "global";

    var params = "mcCode=" + mcCode;
    
    if(isHttps){
        reqUrl = "https://www.samsungdive.com/commonN/getTerms.do";
    }else{
        reqUrl = "http://www.samsungdive.com/commonN/getTerms.do";
    }
    
//      alert(isHttps + "https://www.samsungdive.com====http://www.samsungdive.com");
    var checkPasswrdReq = new Ajax.Request(
                            reqUrl, 
                            {   method: 'post', 
                                parameters: params, 
                                onComplete: resultGetTerms
                            });        
}

function resultGetTerms(response) {
    var f = document.frm_footer;
    
    var result = response.responseText;
    var termText = document.getElementById('agreeForm_01');
    
    if (navigator.userAgent.indexOf('MSIE') > 0) {
        termText.innerText= result;
    } else if (navigator.userAgent.indexOf('Chrome') > 0) { 
        termText.innerText= result;
    } else if (navigator.userAgent.indexOf('Firefox') > 0) {
        result = result.replace(/\n/gi,"<"+"br" +"/>");
        result = result.replace(/&nbsp;/gi," ");
        termText.innerHTML= result;
    } else if (Browser.opera || Browser.safari) {
        result = result.replace(/\n/gi,"<"+"br" +"/>");
        result = result.replace(/&nbsp;/gi," ");
        termText.innerHTML= result;
    } else {
        termText.innerHTML = result;
    }
    f.tempClickTerms.value = "0";
    $('toggleterms01').onclick = getTerms;
    dimLayerShow('terms');
}

function getConditions() {

    var f = document.frm_footer;

    $('toggleConditions01').onclick = "";
    
    if (f.tempClickTerms.value=="Y") {
        return;
    }
    f.tempClickTerms.value="Y";
    
    var mcCode = "global";
    var params = "mcCode=" + mcCode;
    if(isHttps){
        reqUrl = "https://www.samsungdive.com/commonN/getConditions.do";
    }else{
        reqUrl = "http://www.samsungdive.com/commonN/getConditions.do";
    }
    
    var checkPasswrdReq = new Ajax.Request(
                            reqUrl, 
                            {   method: 'post', 
                                parameters: params, 
                                onComplete: resultGetConditions
                            });
}

function resultGetConditions(response) {
    var f = document.frm_footer;
    
    var result = response.responseText;
    var termText = document.getElementById('conditions_01');
    
    if (navigator.userAgent.indexOf('MSIE') > 0) {
        termText.innerText= result;
    } else if (navigator.userAgent.indexOf('Chrome') > 0) { 
        termText.innerText= result;
    } else if (navigator.userAgent.indexOf('Firefox') > 0) {
        result = result.replace(/\n/gi,"<"+"br" +"/>");
        result = result.replace(/&nbsp;/gi," ");
        termText.innerHTML= result;
    } else if (Browser.opera || Browser.safari) {
        result = result.replace(/\n/gi,"<"+"br" +"/>");
        result = result.replace(/&nbsp;/gi," ");
        termText.innerHTML= result;
    } else {
        termText.innerHTML = result;
    }
    
    $('toggleConditions01').onclick = getConditions;
    f.tempClickTerms.value = "0";
    dimLayerShow('conditions');
    }

	function dimLyaerMove(targetElement) {
	dimLayerFixLocation(targetElement);
}
    function dimLayerShow(o) {
            
            var targetElement = document.getElementById(o);

            document.getElementById(o).parentNode.removeChild(document.getElementById(o));
            document.body.insertBefore(targetElement,document.getElementById('wrap'));
        
        var tmpDivision = document.createElement('div');
        tmpDivision.setAttribute('id',"dimBlank");
        //tmpDivision.onclick = function() { dimLayerClose(targetElement); }


        document.body.insertBefore(tmpDivision,document.getElementById('wrap'));
        tmpDivision.style.display = "block";
        
        tmpDivision.className = "dimBackgroundStyle";
        tmpDivision.style.width = "100%";

        //alert(document.getElementsByTagName('wrap').scrollTop);
        //tmpDivision.style.height = document.getElementById('cntWrap').clientHeight +"px";
        //if(document.getElementById('wrap').clientHeight > document.documentElement.clientHeight){
        if(document.body.clientHeight > document.documentElement.clientHeight){
        	tmpDivision.style.height = document.body.clientHeight + "px";
            //tmpDivision.style.height = document.getElementById('wrap').scrollHeight +"px";
            var type='cnt';
        }else{
            tmpDivision.style.height = document.documentElement.clientHeight +"px";
            var type='wrapper';
        }
        //alert(tmpDivision.style.height+'/'+type)

//          if(BrowserDetect.browser=="Explorer" && BrowserDetect.version <8 ) {
//              tmpDivision.style.height = document.getElementById('cntWrap').offsetHeight +18 + "px";
//              tmpDivision.style.height = document.body.clientHeight +18 + "px";
//          } else {
//              tmpDivision.style.height = document.body.clientHeight +"px";
//              //tmpDivision.style.height = document.getElementById('cntWrap').offsetHeight +"px";
//          }

        
        tmpDivision.style.visibility = "visible";
        tmpDivision.style.display = "block";
        
        var targetElement = document.getElementById(o);
        if(!targetElement.className.match("layerStyle")) targetElement.className =  targetElement.className + " layerStyle";

        targetElement.style.visibility = "hidden";
        targetElement.style.display = "block";
        
        dimLayerFixLocation(targetElement); 
        targetElement.style.visibility = "visible";
        
        window.onscroll = window.onresize = function(e) { dimLyaerMove(targetElement) }
        
		var selectRefresh = targetElement.getElementsByTagName('select');
		//fakeselect.initialize();
		for(i=0,j=selectRefresh.length;i<j;i++) {
			selectRefresh[i].reset();
		}

}

	function dimLayerFixLocation(targetElement) {

	var targetXmatrix = parseInt(targetElement.offsetWidth,10);
	var targetYmatrix = parseInt(targetElement.offsetHeight,10);

	var originX = parseInt(document.documentElement.clientWidth,10);
	var originY = parseInt(document.documentElement.clientHeight,10);
	
	var finalX = (originX - targetXmatrix)/2;
	var finalY = (originY - targetYmatrix)/2;
	
	targetElement.style.left = finalX + "px";
	var getmoveScroll;

	if(BrowserDetect.browser=="Chrome"  || BrowserDetect.browser=="Safari") { 
		getmoveScroll = document.body.scrollTop;
	} else {
		getmoveScroll = document.documentElement.scrollTop;
	}
	targetElement.style.top = finalY + getmoveScroll + "px";
	
}


function dimLayerClose(targetElement) {
	
	var dimLayerElement = document.getElementById('dimBlank');
	dimLayerElement.style.display = "none";
	document.body.removeChild(dimLayerElement);
	targetElement.style.display = "none";
	
}

/* 2012-02-14 */
function DropDownMenu1(id) {

    /* Type of the menu: "horizontal" or "vertical" */
    this.type = "horizontal";

    /* Delay (in miliseconds >= 0): show-hide menu */
    this.delay = {
        "show": 0,
        "hide": 300
    }
    /* Change the default position of sub-menu by Y pixels from top and X pixels from left
     * Negative values are allowed */
    /* this.position = {
        "top": -4,
        "left": 0
    } */
    /* Z-index property for .section */
    this.zIndex = {
        "visible": 1,
        "hidden": -1
    };

    // Browser detection
    this.browser = {
        "ie": Boolean(document.body.currentStyle),
        "ie5": (navigator.appVersion.indexOf("MSIE 5.5") != -1 || navigator.appVersion.indexOf("MSIE 5.0") != -1)
    };
    if (!this.browser.ie) { this.browser.ie5 = false; }

    /* Initialize the menu */
    this.init = function() {
        if (!document.getElementById(this.id)) { return alert("DropDownMenu1.init() failed. Element '"+ this.id +"' does not exist."); }
        if (this.type != "horizontal" && this.type != "vertical") { return alert("DropDownMenu1.init() failed. Unknown menu type: '"+this.type+"'"); }
        if (this.browser.ie && this.browser.ie5) { fixWrap(); }
        fixSections();
        parse(document.getElementById(this.id).childNodes, this.tree, this.id);
    }

    /* Search for .section elements and set width for them */
    function fixSections() {
        var arr = document.getElementById(self.id).getElementsByTagName("ul");
        var sections = new Array();
        var widths = new Array();
        
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].className == "section") {
                sections.push(arr[i]);
            }
        }
        for (var i = 0; i < sections.length; i++) {
            widths.push(getMaxWidth(sections[i].childNodes));
        }
        for (var i = 0; i < sections.length; i++) {
            sections[i].style.width = (widths[i]) + "px";
        }
        if (self.browser.ie) {
            for (var i = 0; i < sections.length; i++) {
                setMaxWidth(sections[i].childNodes, widths[i]);
            }
        }
    }

    function fixWrap() {
        var elements = document.getElementById(self.id).getElementsByTagName("a");
        for (var i = 0; i < elements.length; i++) {
            if (/item2/.test(elements[i].className)) {
                elements[i].innerHTML = '<div nowrap="nowrap">'+elements[i].innerHTML+'</div>';
            }
        }
    }

    /* Search for an element with highest width among given nodes, return that width */
    function getMaxWidth(nodes) {
        var maxWidth = 0;
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].nodeType != 1) { continue; }
            if (nodes[i].offsetWidth > maxWidth) { maxWidth = nodes[i].offsetWidth; }
        }
        return maxWidth;
    }

    /* Set width for item2 elements */
    function setMaxWidth(nodes, maxWidth) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].nodeType == 1 && /item2/.test(nodes[i].className) && nodes[i].currentStyle) {
                if (self.browser.ie5) {
                    nodes[i].style.width = (maxWidth) + "px";
                } else {
                    nodes[i].style.width = (maxWidth - parseInt(nodes[i].currentStyle.paddingLeft) - parseInt(nodes[i].currentStyle.paddingRight)) + "px";
                }
            }
        }
    }

    /* Parse nodes, create events, position elements */
    function parse(nodes, tree, id) {
        for (var i = 0; i < nodes.length; i++) {
            if (1 != nodes[i].nodeType) {
                continue;
            }
            switch (true) {
                // .item1
                case /\bitem1\b/.test(nodes[i].className):
                    nodes[i].id = id + "-" + tree.length;
                    tree.push(new Array());
                    nodes[i].onmouseover = item1over;
                    nodes[i].onmouseout = item1out;
                    break;
                // .item2
                case /\bitem2\b/.test(nodes[i].className):
                    nodes[i].id = id + "-" + tree.length;
                    tree.push(new Array());
                    break;
                // .section
                case /\bsection\b/.test(nodes[i].className):
                    // id, events
                    nodes[i].id = id + "-" + (tree.length - 1) + "-section";
                    nodes[i].onmouseover = sectionOver;
                    nodes[i].onmouseout = sectionOut;
                    // position
                    /* var box1 = document.getElementById(id + "-" + (tree.length - 1));
                    var box2 = document.getElementById(nodes[i].id);
                    if ("horizontal" == self.type) {
                        box2.style.top = box1.offsetTop + box1.offsetHeight + self.position.top + "px";
                        if (self.browser.ie5) {
                            box2.style.left = self.position.left + "px";
                        } else {
                            box2.style.left = box1.offsetLeft + self.position.left + "px";
                        }
                    } else if ("vertical" == self.type) {
                        box2.style.top = box1.offsetTop + self.position.top + "px";
                        if (self.browser.ie5) {
                            box2.style.left = box1.offsetWidth + self.position.left + "px";
                        } else {
                            box2.style.left = box1.offsetLeft + box1.offsetWidth + self.position.left + "px";
                        }
                    } */
                    // sections, sectionsShowCnt, sectionsHideCnt
                    self.sections.push(nodes[i].id);
                    self.sectionsShowCnt.push(0);
                    self.sectionsHideCnt.push(0);
                    break;
            }
            if (nodes[i].childNodes) {
                if (/\bsection\b/.test(nodes[i].className)) {
                    parse(nodes[i].childNodes, tree[tree.length - 1], id + "-" + (tree.length - 1));
                } else {
                    parse(nodes[i].childNodes, tree, id);
                }
            }
        }
    }

    /* event, item1:onmouseover */
    function item1over() {
        var id_section = this.id + "-section";
        if (self.visible) {
            var el = new Element(self.visible);
            el = document.getElementById(el.getParent().id);
            if (/item1-active/.test(el.className)) {
                el.className = el.className.replace(/item1-active/, "item1");
            }
        }
        if (self.sections.contains(id_section)) {
            self.sectionsHideCnt[self.sections.indexOf(id_section)]++;
            var cnt = self.sectionsShowCnt[self.sections.indexOf(id_section)];
            setTimeout(function(a, b) { return function() { self.showSection(a, b); } } (id_section, cnt), self.delay.show);
        } else {
            if (self.visible) {
                var cnt = self.sectionsHideCnt[self.sections.indexOf(self.visible)];
                setTimeout(function(a, b) { return function() { self.hideSection(a, b); } } (self.visible, cnt), self.delay.show);
            }
        }
    }

    /* event, item1:onmouseout */
    function item1out() {
        var id_section = this.id + "-section";
        if (self.sections.contains(id_section)) {
            self.sectionsShowCnt[self.sections.indexOf(id_section)]++;
            if (id_section == self.visible) {
                var cnt = self.sectionsHideCnt[self.sections.indexOf(id_section)];
                setTimeout(function(a, b) { return function() { self.hideSection(a, b); } }(id_section, cnt), self.delay.hide);
            }
        }
    }

    /* event, section:onmouseover */
    function sectionOver() {
        self.sectionsHideCnt[self.sections.indexOf(this.id)]++;
        var el = new Element(this.id);
        el = document.getElementById(el.getParent().id);
        if (!/item1-active/.test(el.className)) {
            el.className = el.className.replace(/item1/, "item1-active");
        }
    }

    /* event, section:onmouseout */
    function sectionOut() {
        self.sectionsShowCnt[self.sections.indexOf(this.id)]++;
        var cnt = self.sectionsHideCnt[self.sections.indexOf(this.id)];
        setTimeout(function(a, b) { return function() { self.hideSection(a, b); } }(this.id, cnt), self.delay.hide);
    }

    /* Show section (1 argument passed)
     * Try to show section (2 arguments passed) - check cnt with sectionShowCnt */
    this.showSection = function(id, cnt) {
        if (typeof cnt != "undefined") {
            if (cnt != this.sectionsShowCnt[this.sections.indexOf(id)]) { return; }
        }
        this.sectionsShowCnt[this.sections.indexOf(id)]++;
        var el = new Element(id);
        var parent = document.getElementById(el.getParent().id);
        if (!/item1-active/.test(parent.className)) {
            parent.className = parent.className.replace(/item1/, "item1-active");
        }
        if (this.visible) {
            if (id == this.visible) { return; }
            this.hideSection(this.visible);
        }
        //document.getElementById(id).style.display = "block";
        document.getElementById(id).style.visibility = "visible";
        document.getElementById(id).style.zIndex = this.zIndex.visible;
        this.visible = id;
    }

    /* Hide section (1 argument passed)
     * Try to hide section (2 arguments passed) - check cnt with sectionHideCnt */
    this.hideSection = function(id, cnt) {
        if (typeof cnt != "undefined") {
            if (cnt != this.sectionsHideCnt[this.sections.indexOf(id)]) { return; }
        }
        var el = new Element(id);
        var parent = document.getElementById(el.getParent().id);
        parent.className = parent.className.replace(/item1-active/, "item1");
        document.getElementById(id).style.zIndex = this.zIndex.hidden;
        document.getElementById(id).style.visibility = "hidden";
        //document.getElementById(id).style.display = "none";
        if (id == this.visible) { this.visible = ""; }
        else {
            //throw "DropDownMenu1.hideSection('"+id+"', "+cnt+") failed, cannot hide element that is not visible";
            return;
        }
        this.sectionsHideCnt[this.sections.indexOf(id)]++;
    }

    /* Necessary when showing section that doesn't exist - hide currently visible section. See: item1over() */
    this.hideSelf = function(cnt) {
        if (this.visible && cnt == this.sectionsHideCnt[this.sections.indexOf(this.visible)]) {
            this.hideSection(this.visible);
        }
    }

    /* Element (.section, .item2 etc) */
    function Element(id) {
        /* Get parent element */
        this.getParent = function() {
            var s = this.id.substr(this.menu.id.length);
            var a = s.split("-");
            a.pop();
            return new Element(this.menu.id + a.join("-"));
        }
        this.menu = self;
        this.id = id;
    }

    var self = this;
    this.id = id; /* menu id */
    this.tree = []; /* tree structure of menu */
    this.sections = []; /* all sections, required for timeout */
    this.sectionsShowCnt = [];
    this.sectionsHideCnt = [];
    this.visible = ""; /* visible section, ex. menu-0-section */
}

/* Finds the index of the first occurence of item in the array, or -1 if not found */
if (typeof Array.prototype.indexOf == "undefined") {
    Array.prototype.indexOf = function(item) {
        for (var i = 0; i < this.length; i++) {
            if ((typeof this[i] == typeof item) && (this[i] == item)) {
                return i;
            }
        }
        return -1;
    }
}

/* Check whether array contains given string */
if (typeof Array.prototype.contains == "undefined") {
    Array.prototype.contains = function(s) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === s) {
                return true;
            }
        }
        return false;
    }
}